<template>
  <div>
    <div style="position: absolute;top: 10px;left: 30px">
      <p style="font-size: 25px">后台管理系统登录</p>
    </div>
    <div style="height: 80px"></div>

        <el-row type="flex">
          <div>
              <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                <el-form-item label="用户名:" prop="username">
                  <el-input v-model="ruleForm.name" style=""></el-input>
                </el-form-item>
                <el-form-item label="密码:" prop="pass">
                  <el-input type="password" v-model="ruleForm.password" autocomplete="off" style=""></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')" style="width:100%">登录</el-button>
                </el-form-item>
              </el-form>
          </div>
        </el-row>
  </div>
</template>

<script>
import {setToken} from "@/utils/Token";
import {login} from "@/api/admin_api";

export default {
  name: "admin_login",
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }
      callback();
    };
    return {
      ruleForm: {
        password: '',
        name: ''
      },
      rules: {
        password: [
          {validator: validatePass, trigger: 'blur'}
        ],
        name: [
          {validator: checkUsername, trigger: 'blur'}
        ]
      }
    };
  },

  created() {

  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.ruleForm).then((res) => {
            console.log("name: "+this.ruleForm.name);
            console.log("password: "+this.ruleForm.password)
            if (res.data.status === 200){
              setToken('userId',res.data.data.id)
              setToken('token',res.data.token)
              this.$message({
                          message: '管理员登录成功！',
                          type: 'success'
                        });
              this.$router.push('/admin');
            }else {
                      console.log(res.data.msg);
                    }

          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  }
}
</script>

<style scoped>

</style>